//
//  ADRequest.m
//  iCarStyle
//
//  Created by liunian on 13-9-6.
//  Copyright (c) 2013年 liunian. All rights reserved.
//

#import "ADRequest.h"
#import "HttpRequest.h"

#define apiSource @"http://imitao.sinaapp.com/api/jdong_cover/list/"
@interface ADRequest ()
@property (nonatomic , assign) id<ReqDelegate>delegate;
@end
@implementation ADRequest
- (void)requestADWithDelegate:(id<ReqDelegate>)delegate;{
    _delegate = nil;
    _delegate = delegate;
    
    NSMutableDictionary *param = [[NSMutableDictionary alloc] initWithCapacity:0];
    SET_PARAM(@"50", @"count", param);
    SET_PARAM(@"asc", @"ord", param);
    SET_PARAM(@"index", @"by", param);
    [HttpRequest requestWithURLStr:apiSource
                             param:param
                        httpMethod:HttpMethodGet
                            isAsyn:YES
                   completionBlock:^(ASIHTTPRequest *request) {
                       NSDictionary *jsonDict = [request.responseString JSONValue];
                       
                       if ([HttpRequest isRequestSuccess:request]) {
                           NSMutableArray *rstArray = [NSMutableArray arrayWithCapacity:0];
                           if ([[jsonDict objectForKey:@"data"] isKindOfClass:[NSDictionary class]]) {
                               NSArray  *sources = [[jsonDict objectForKey:@"data"] objectForKey:@"items"];
                               if (isArrayWithCountMoreThan0(sources)) {
                                   for (NSDictionary *dic in sources) {
                                       if (isDictWithCountMoreThan0(dic)) {
                                           AdItem *s = [AdItem createWithDict:dic];
                                           [rstArray addObject:s];
                                       }
                                   }
                                   
                                   if ([_delegate respondsToSelector:@selector(finishADReq:ads:)]) {
                                       [_delegate finishADReq:self ads:rstArray];
                                   }
                               }
                           }else{
                               if ([_delegate respondsToSelector:@selector(finishErrorReq:errorCode:message:)]) {
                                   [_delegate finishErrorReq:self errorCode:1 message:@"无数据"];
                               }
                           }
                       }
                   } failedBlock:^(ASIHTTPRequest *request) {
                       if ([_delegate respondsToSelector:@selector(finishErrorReq:errorCode:message:)]) {
                           [_delegate finishErrorReq:self errorCode:1 message:@"无数据"];
                       }
                   }];
}
@end
